//name: Xingkai Zhou
//SID:1318620

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(11223)) {
            Resource resource = new Resource();
            System.out.println("Server listening on port 11223 for a connection...");
            while (true) {
                new Thread(new serverThread(serverSocket.accept(), resource)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class serverThread implements Runnable {
    private Socket socket;
    private Resource resource;

    serverThread(Socket socket, Resource resource) {
        this.socket = socket;
        this.resource = resource;
        System.out.println("Client" + hashCode() + "is connected...with IP:" + socket.getInetAddress());
    }

    @Override
    public void run() {
        try (ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())) {
            while (true) {
                QueryRequest request = (QueryRequest) inputStream.readObject();
                switch (request.getType()) {
                    case SELECT:
                        outputStream.writeObject(resource.queryById(request.getWord()));
                        break;
                    case DELETE:
                        outputStream.writeObject(resource.deleteById(request.getWord()));
                        break;
                    case UPDATE:
                        outputStream.writeObject(resource.update(request.getWord(), request.getExplain()));
                        break;
                    case SAVE:
                        outputStream.writeObject(resource.save(request.getWord(), request.getExplain()));
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error：" + e + ",Client" + hashCode() + "is disconnected...");
        }
    }
}
